import React, { useState, useEffect } from 'react';
import { Table, Button, Card, Tag, Select, message } from 'antd';
import { api } from '../utils/api';

const { Option } = Select;

interface Leaderboard {
  id: number;
  user_id: number;
  username: string;
  score: number;
  rank_position: number;
  period_type: string;
  period_value: string;
}

const LeaderboardManagement: React.FC = () => {
  const [leaderboards, setLeaderboards] = useState<Leaderboard[]>([]);
  const [loading, setLoading] = useState(false);
  const [periodType, setPeriodType] = useState('all_time');
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  useEffect(() => {
    fetchLeaderboards();
  }, [periodType, pagination.current, pagination.pageSize]);

  const fetchLeaderboards = async () => {
    try {
      setLoading(true);
      const response = await api.get('/leaderboards/admin/', {
        params: {
          page: pagination.current,
          per_page: pagination.pageSize,
          period_type: periodType
        }
      });
      if (response.data.success) {
        setLeaderboards(response.data.data.items);
        setPagination(prev => ({ ...prev, total: response.data.data.total }));
      }
    } catch (error) {
      message.error('获取排行榜失败');
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    {
      title: '排名',
      dataIndex: 'rank_position',
      key: 'rank_position',
      width: 80
    },
    {
      title: '用户',
      dataIndex: 'username',
      key: 'username',
      width: 120
    },
    {
      title: '分数',
      dataIndex: 'score',
      key: 'score',
      width: 100
    },
    {
      title: '周期',
      dataIndex: 'period_type',
      key: 'period_type',
      width: 100,
      render: (type: string) => {
        const map: any = { all_time: '总榜', month: '月榜', week: '周榜' };
        return <Tag color="blue">{map[type] || type}</Tag>;
      }
    },
    {
      title: '周期值',
      dataIndex: 'period_value',
      key: 'period_value',
      width: 120
    }
  ];

  return (
    <div>
      <Card title="排行榜管理" extra={
        <Select value={periodType} onChange={setPeriodType} style={{ width: 120 }}>
          <Option value="all_time">总榜</Option>
          <Option value="month">月榜</Option>
          <Option value="week">周榜</Option>
        </Select>
      }>
        <Table
          columns={columns}
          dataSource={leaderboards}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`
          }}
          onChange={(pagination) => {
            setPagination(prev => ({ ...prev, current: pagination.current || 1, pageSize: pagination.pageSize || 10 }));
          }}
        />
      </Card>
    </div>
  );
};

export default LeaderboardManagement; 